package com.lzxuni;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SpringBootTest
@RunWith(SpringRunner.class)
public class AAAMpGenerator {

    @Value("${spring.datasource.druid.first.url}")
    private String sqlUrl;
    @Value("${spring.datasource.druid.first.username}")
    private String userName;
    @Value("${spring.datasource.druid.first.password}")
    private String passWord;
    private String idName="";

    @Autowired
    public DataSource dataSource;

    //作者名称
    private String author="LaoNa";
    //所在包
    private String packageName="com.lzxuni.modules.plantingprogram";
    //访问根路径
    private String rootUrl ="/PlantingProgram";

    //表名
    private String tableName ="tbl_planting_program_detail";




    @Test
    public void t() throws SQLException {
        PreparedStatement ps = dataSource.getConnection().prepareStatement("select column_name from information_schema.`COLUMNS` where table_name='"+tableName+"' and column_key='PRI'");
        ResultSet set = ps.executeQuery();
        while(set.next()) {
            String i = set.getString(1);
            idName=lineToHump(i);
        }
        //需要创建的表名
        makeCode(tableName);
    }

    public void makeCode(String... tableNames) {
        //代码生成器
        AutoGenerator mpg = new AutoGenerator();
        //数据源配置
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.MYSQL);
        dataSourceConfig.setUrl(sqlUrl);
        dataSourceConfig.setUsername(userName);
        dataSourceConfig.setPassword(passWord);
        dataSourceConfig.setDriverName("com.mysql.jdbc.Driver");
        mpg.setDataSource(dataSourceConfig);
        //全局配置
        GlobalConfig config = new GlobalConfig();
        config.setActiveRecord(false);    //活动记录模式
        config.setAuthor("LaoNa");   //作者注释
        config.setEnableCache(false);  //关闭 二级缓存
        config.setOutputDir("D:\\MpGenerator");  //文件生成目录
        config.setFileOverride(true);   //覆盖已有文件
        config.setIdType(IdType.UUID);   //主键策略
        config.setServiceName("%sService");
        mpg.setGlobalConfig(config);

        //数据库表配置
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setCapitalMode(true);  //是否大写命名
        strategyConfig.setEntityLombokModel(true); //是否为lombok模型
        strategyConfig.setNaming(NamingStrategy.underline_to_camel); //数据库表映射到实体的命名策略  下换线转驼峰
        strategyConfig.setInclude(tableNames); //表名
        strategyConfig.setTablePrefix(new String[]{"base_","tbl_"});//表前缀
        strategyConfig.setRestControllerStyle(true);
		//strategyConfig.setCapitalMode(true);  //全局大写
        strategyConfig.setEntityBuilderModel(true);   //链式模型 chainModel
        strategyConfig.setSuperControllerClass("com.lzxuni.modules.common.controller.BaseController");
        mpg.setStrategy(strategyConfig);

        PackageConfig pc = new PackageConfig();
        pc.setParent(packageName);
        pc.setController("controller");
        pc.setEntity("entity");
        mpg.setPackageInfo(pc);

        // 自定义配置 开始-----------------


        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String,Object> map=new HashMap<>();
                map.put("rootUrl",rootUrl);
                map.put("chainModel",true);
                map.put("idName",idName);
                this.setMap(map);
            }
        };
        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig("/templates/controller.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return config.getOutputDir() + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Controller.java";
            }
        });
        focList.add(new FileOutConfig("/templates/entity.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return config.getOutputDir() + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + ".java";
            }
        });

        focList.add(new FileOutConfig("/templates/service.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return config.getOutputDir() + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Service.java";
            }
        });
        focList.add(new FileOutConfig("/templates/serviceImpl.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return config.getOutputDir() + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "ServiceImpl.java";
            }
        });
        focList.add(new FileOutConfig("/templates/mapper.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return config.getOutputDir() + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper.java";
            }
        });
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return config.getOutputDir() + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper.xml";
            }
        });

        cfg.setFileOutConfigList(focList);

        mpg.setCfg(cfg);
        // 自定义配置 开始-----------------

        mpg.execute();
    }

    public static String lineToHump(String str) {
        str = str.toLowerCase();
        Pattern linePattern = Pattern.compile("_(\\w)");
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString().substring(0, 1).toUpperCase()+sb.toString().substring(1);

    }
}
